Grantsfire.maps = {};

Grantsfire.maps.init = function (mapid) {
	if (! GBrowserIsCompatible()) {
		$(mapid).innerHTML = "Sorry, the mapping functionality is not compatible with your browser";
		return;
	}
	
	var map = new GMap2($(mapid));
    map.setCenter(new GLatLng(37.4419, -122.1419), 13);
	map.setZoom(2);

 	map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());

	Grantsfire.maps.loadGrantData(map);
};

Grantsfire.maps.loadedGrantData = function (map, req) {
	if (req.readyState != 4)
		return;
		
	var xmlDoc = GXml.parse(req.responseText);
	var grants = xmlDoc.documentElement.getElementsByTagName("grant");
	
	var mgr = new MarkerManager(map);
	var newMarkers = [];
	
	for (var i = 0; i < grants.length; i++) {
        var grant = grants[i];
        if (! grant)
            continue;

		var lat = parseFloat(grant.getAttribute("lat"));
		var lng = parseFloat(grant.getAttribute("lon"));
	
		if (! lat || ! lng)
			continue;
		
		var point = new GLatLng(lat, lng);
		
        var title = grant.getAttribute("title");
        var amount = grant.getAttribute("amount");
        var currency = grant.getAttribute("currency");
        if (! currency) currency = "USD";
        var country = grant.getAttribute("adr_country_name");
        var locality = grant.getAttribute("adr_locality");

		var marker = new GMarker(point, {
               title: title
        });

        var desc = "<p><b>" + title + "</b></p><p>";

        if (country)
            desc += "Country: " + country + "<br/>";

        if (locality)
            desc += "Locality: " + locality + "<br/>";        

        if (amount)
            desc += "Amount: " + amount + currency + "<br/>";        

        desc += "</p>";

        marker.bindInfoWindowHtml(desc);

        newMarkers.push(marker);
	}
	
	mgr.addMarkers(newMarkers, 1);
	mgr.refresh();
}

Grantsfire.maps.markerClicked = function (marker) {
    
}

Grantsfire.maps.loadGrantData = function (map) {
	if (! $("mapDataUri") || ! $("mapDataParams"))
		return;

	var mapDataUri = $("mapDataUri").value;
	var mapDataParams = $("mapDataParams").value;
	
	if (! mapDataUri)
		return;
		
	if (mapDataParams)
		mapDataUri += "?geocode=1&" + mapDataParams;
	
	var request = GXmlHttp.create();
    request.open("GET", mapDataUri, true);
	request.onreadystatechange = function () { Grantsfire.maps.loadedGrantData(map, request) };
	request.send({});
}
